package demo.service;

import cn.hutool.core.util.RandomUtil;
import demo.Result;
import demo.entity.Seek;
import demo.repository.SeekRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SeekService {
    @Autowired
    SeekRepository seekRepository;

    public Result save(Long uid, Long companyId) {
        String invitingCode;
        for (int i = 0; i < 10; i++) {
            invitingCode = RandomUtil.randomString(5);
            if (!seekRepository.existsByInvitingCodeAndValidIsTrue(invitingCode)) {
                Seek seek = new Seek();
                seek.setUid(uid);
                seek.setCompanyId(companyId);
                seek.setInvitingCode(invitingCode);
                seek.setValid(true);
                seek.setDate(new Date());
                seekRepository.save(seek);
                return Result.success("邀请码生成成功", seek);
            }
        }
        return Result.error("邀请码生成失败");
    }

    /**
     * 更新 seek 对象
     *
     * @param seek seek 对象
     */
    public void update(Seek seek) {
        seekRepository.save(seek);
    }

    public Result findByInvitingCode(String invitingCode) {
        List<Seek> seeks = seekRepository.findSeeksByInvitingCodeAndValidIsTrue(invitingCode);
        if (seeks.isEmpty()) {
            return Result.error("没有找到邀请码");
        }

        return Result.success("邀请码已找到", seeks.get(0));
    }

    public Result findByUidAndCompanyId(Long uid, Long companyId) {
        List<Seek> seeks = seekRepository.findSeeksByUidAndCompanyIdAndValidIsTrue(uid, companyId);
        if (seeks.isEmpty()) {
            return Result.error("没有找到邀请码");
        }
        return Result.success("邀请码已找到", seeks.get(0));
    }
}
